#copyright by Staszek (assimilated.pl)
import ekg
import MySQLdb
from random import randint

save_pass = 'haslo+potrzebne+do+zapisania+sie'
connection = None
user_names = {}
user_nicks = {} 
bofhs = []

def connect():
        global connection
        connection = MySQLdb.connect ( host = "localhost",
                        user = "uzytkownik+bazy+danych",
                        passwd = "haslo+do+bazy",
                        db = "nazwa+bazy+danych",
                        charset = 'utf8')

def query(sql):
        global connection
        try:
                cursor = connection.cursor()
        except MySQLdb.OperationalError:
                connect()
                cursor = connection.cursor()
        cursor.execute(sql)
        return cursor.fetchall()

def bofh():
        if len(bofhs) < 1:
                f = open('/home/staszek/bofh.txt')
                try:
                        for line in f:
                                bofhs.append(line)
                finally: 
                        f.close()
        return bofhs[ randint(0, len(bofhs) - 1)]

def users(update = False):
        global user_names
        global user_nicks
        if (update or len(user_names) < 1):
                for row in query('select nick, number from users'):
                        user_names[row[0]] = row[1]
                        user_nicks[str(row[1])] = row[0]
        return user_names

def remove(uid):
        query('delete from users where number = "%s" limit 1' % str(uid))

def send_msg(uid, msg):
        ekg.command('chat %s %s' % (uid, msg))

def save(uid, nick):
        query('insert into users (nick, number) values("%s", "%s")' % (nick, uid))
        users(update = True)

def handle_msg(uin, name, msgclass, text, time, secure):
        global user_names
        global save_pass
        global user_nicks
        try:
                command = text.split(' ', 1)[0]
                msg = text.split(' ', 1)[1]
        except IndexError:
                command = text
                pass

        if command == 'zapisz':
                password, nick = msg.split(' ', 1)
                if password == save_pass:
                        save(uin, nick)
                        send_msg(uin, 'Zapisano')
                else:
                        send_msg(uin, 'Wrong passwd')

        if not str(uin) in user_nicks:
                return True

        if command == 'zapisani':
                nicks = [nick for nick in user_names]
                send_msg(uin, ', '.join(nicks))
        elif command == 'wypisz':
                remove(uin)
                send_msg(uin, 'Usunieto')
        elif command == 'ping':
                send_msg(uin, 'pong')
        elif command == 'bofh':
                send_msg(uin, bofh())
        elif command == 'msg':
                for nick in user_names:
                        if str(uin) != user_names[nick]:
                                send_msg(user_names[nick], '[%s] %s' % (user_nicks[str(uin)], msg))
        else:
                for nick in user_names:
                        if str(uin) != user_names[nick]:
                                send_msg(user_names[nick], '[%s] %s' % (user_nicks[str(uin)], text))

def init():
        ekg.printf('generic', 'Zaladowano bota')
        connect()
        users(update = True)

def deinit():
        ekg.printf('generic', 'Buuu... nie wylaczaj mnie :(')
        connection.close()
init()
